/******************************************************************************
 * Copyright (C) 2015  671643387@qq.com
 *
 * This program is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License as published by the
 * Free Software Foundation; either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
 * more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with this program; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 *****************************************************************************/

#include "MySQLConnection.h"

namespace UGame {
namespace Data {
namespace Rel {


    bool MySQLConnection::Open(const std::string& _Host,
        const std::string& _Port, const std::string& _User,
        const std::string _Password, const std::string& _Db)
    {
        _res = mysql_init(NULL);

        do
        {
            std::string _LHost;
            int _Lport;
            const char* _UnixSocket;

            mysql_options(_res, MYSQL_SET_CHARSET_NAME, "utf8");
            mysql_options(_res, MYSQL_OPT_RECONNECT, "1");

            if (_Host == ".")                                        // socket use option (Unix/Linux)
            {
                unsigned int _Opt = MYSQL_PROTOCOL_SOCKET;
                mysql_options(_res, MYSQL_OPT_PROTOCOL, (char const*)&_Opt);
                _LHost = "localhost";
                _Lport = 0;
                _UnixSocket = _Port.c_str();
            }
            else                                                    // generic case
            {
                _LHost = _Host;
                _Lport = atoi(_Port.c_str());
                _UnixSocket = NULL;
            }

            /* Auto reconnect */
            char _Value = 1;
            mysql_options(_res, MYSQL_OPT_RECONNECT, &_Value);

            /* Real connect */
            if (!mysql_real_connect(_res, _LHost.c_str(), _User.c_str(),
                _Password.c_str(), _Db.c_str(), _Lport, _UnixSocket, 0))
            {
                _errCode = mysql_errno(_res);
                _errString = mysql_error(_res);
                mysql_close(_res);
                _res = NULL;
                _ReportError();
                break;
            }

        } while (false);

        return _res != NULL;
    }

}}}
